package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setMealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * @param dishDTO
     */
    /*因为涉及到两张表，所以加事务注解*/
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //1、向菜品表添加一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);//属性命名一致才能拷贝
        dishMapper.insert(dish);

        //3、获取insert语句生成的主键值
        Long dishId = dish.getId();

        //向口味表插入多条数据
        //2.1、得到口味集合
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //2.2、判断集合是否有数据
        if (flavors != null && flavors.size() > 0){//有口味数据
            /*4、有主键值后，需要用dishId为DishFlavor里边每一个id属性赋值*/
            flavors.forEach(dishFlavor -> {//遍历的每一项为dishFlavor
                //具体做的事情
                dishFlavor.setDishId(dishId);
            });

            //这时候插入n条数据
            //2.3、不需要遍历集合一条条插入，可以直接批量插入
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     分页查询菜品
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     删除菜品
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //1、判断当前菜品是否可以删除--->是否正在起售
        //1.1、遍历得到每一个菜品id
        for (Long id : ids) {
            //1.2、根据菜品id得到菜品
            Dish dish = dishMapper.getById(id);
            //1.3、如果菜品正在起售，则抛出业务异常
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //2、判断当前菜品是否可以删除--->是否关联了套餐。套餐与菜品多对多的关系
        List<Long> setMealIds = setMealDishMapper.getSetMealIdsByDishIds(ids);
        //2.1、如果查到了集合不为空，长度大于0，证明关联了套餐，抛异常
        if (setMealIds.size() > 0 && setMealIds != null) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //3、可以删除
        /*缺点：每一次遍历都要操作数据库，影响性能*/
       /* for (Long id : ids) {
            dishMapper.deleteById(id);
            //4、将菜品关联的口味数据批量删除
            dishFlavorMapper.deleteByDishId(id);
        }*/

        /*优化代码：*/
        //5、可以删除，根据菜品id集合批量删除菜品数据
        //sql:delete from dish where id in (?,?,?)
        dishMapper.deleteByIds(ids);

        //6、根据菜品id集合批量删除菜品关联的口味数据
        //sql:delete from dish_flavor where dish_id in (?,?,?)
        dishFlavorMapper.deleteByDishIds(ids);
    }


    /*根据id查询菜品和对应的口味数据*/
    public DishVO getByIdWithFlavor(Long id) {
        //可以分两次查询，1；查询菜品表的基础属性   2：根据菜品id查询关联的口味数据  3、将两部分数据封装到一起
        //1根据id查询菜品数据
        Dish dish = dishMapper.getById(id);

        //2根据id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);//因为一种菜品对应多种口味，所以返回值是List集合

        //3将查询到数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /*根据id修改菜品基本信息和口味信息*/
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        //1.1
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //1、修改菜品基本信息
        dishMapper.update(dish);

        //2、删除原有的口味数据(根据菜品id作为条件来删除)
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //3、重新插入口味数据(新的口味数据在DTO中已经传过来了
        List<DishFlavor> flavors = dishDTO.getFlavors();//得到口味数据
        //5、判断是否存在口味数据，存在则插入
        if (flavors != null && flavors.size() > 0) {//有口味数据
            /*4、有主键值后，需要用dishId为DishFlavor里边每一个id属性赋值*/
            flavors.forEach(dishFlavor -> {//遍历的每一项为dishFlavor
                //具体做的事情
                dishFlavor.setDishId(dishDTO.getId());//因为重新设置口味了，有新增的，所以需要设置id
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     菜品起售停售
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        //这里本质是执行修改语句 update dish set status=? where id=?
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE){
            //如果状态是停售，则包含此菜品的套餐也需要停售。
            /*1.1、创建空集合将id放入*/
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setMealDishMapper.getSetMealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

   /*根据分类id查询菜品*/
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
